package com.itheima.controller;

import java.awt.Desktop.Action;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import service.MemberService;

import java.util.Map;

/**
 * ClassName: LoginController
 * Description:登录验证码
 * date: 2019/11/25 18:09
 * Author Airson
 * Since JDK 1.8
 */
@RequestMapping("/login")
@RestController
public class LoginController {

    @Reference
    MemberService memberService;
    //用map接收前段发送的手机号和验证码
    //根据手机号查询redis中保存的验证码,并判断是否正确,如正确
    //判断是否是会员,并自动注册为会员
    @Autowired
    JedisPool jedisPool;


    @RequestMapping("check")
    public Result check(@RequestBody Map<String, String> map) {
        //获取手机号
        String telephone = map.get("telephone");

        //获取表单中的验证码
        String validateCodeInParam = map.get("validateCode");

        //调用jedis中的验证码
        String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_LOGIN + "-" + telephone);

        if (!(validateCodeInParam != null && validateCodeInParam.equals(validateCodeInRedis))) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //验证成功,自动注册为会员
        try {
            memberService.handlermember(map);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
